//
//  YSGameViewController.m
//  Yaoyle
//
//  Created by ZhaoXudong on 14-9-24.
//  Copyright (c) 2014年 ZhaoXudong. All rights reserved.
//

#import "YSGameViewController.h"
#import "YSGameUserView.h"
#import "YSCountDownView.h"
#import "YSUserModel.h"
#import "YSDieResultView.h"
#import "YSSelectQuizView.h"
#import "YSLastResultView.h"
#import "WXApi.h"
#import "WXApiObject.h"
#import "WeiboSDK.h"
#import "YSAppDelegate.h"
#import <AudioToolbox/AudioToolbox.h>

@interface YSGameViewController () <LastResultViewDelegate, UIAlertViewDelegate>{
    eGameStatus gameStatus;
    
    __weak IBOutlet UIButton *soundBtn;
    __weak IBOutlet UILabel *roomInfoLabel;
    __weak IBOutlet UILabel *userName;
    __weak IBOutlet UILabel *userScore;
    __weak IBOutlet UIImageView *headImageView;
    __weak IBOutlet UIImageView *boxImageView;
    __weak IBOutlet UIButton *readyBtn;
    __weak IBOutlet UIView *myView;
    
    NSMutableArray *userViewArray;
    
    UIView *gameBeginView;
    
    BOOL isBeginGame;
    NSMutableString *result;
    YSDieResultView *resultView;
    
    YSSelectQuizView * quizview;
    
    YSLastResultView *lastResultView;
    YSCountDownView *countDownView;
    
    UIButton *closeBtn;
    
    int preDiceNum;
    int preDicePoint;
    
    BOOL isPlaySound;
    
    eShareType shareType;
    
    __weak IBOutlet UIView *msgView;
    __weak IBOutlet UIImageView *msgBs_view;
    __weak IBOutlet UILabel *msgNumLabel;
    __weak IBOutlet UIImageView *myViewBg;
    
}

@end

@implementation YSGameViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        gameStatus = eGameWaiting;
        
        userViewArray = [NSMutableArray array];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(socketOtherStatus:)
                                                     name:kNotificationOtherStatus
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(socketRadioNotification:)
                                                     name:kNotificationSystemRadio
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(shareSuccess)
                                                     name:kNotificationWeiXinShareSuccess
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(shareFail)
                                                     name:kNotificationWeiXinShareFail
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(shareSuccess)
                                                     name:kNotificationWeiBoShareSuccess
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(shareFail)
                                                     name:kNotificationWeiBoShareFail
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(socketFail:)
                                                     name:kNotificationSocketFail
                                                   object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    preDiceNum = 1;
    preDicePoint = 1;
    
    isBeginGame = NO;
    isPlaySound = YES;
    
    msgView.hidden = YES;
    roomInfoLabel.text = [NSString stringWithFormat:@"房间号:%@ 底注:%@",self.roomModel.roomNo,self.roomModel.roomScore];
    userName.text = _userModel.name;
    [self updateUserScore:nil];
    
    if ([YSUtility isBlankObject:_userModel.photoUrl]) {
        if (_userModel.sex == eSexBoy) {
            headImageView.image = [UIImage imageNamed:kDefaultBoyHead];
        } else {
            headImageView.image = [UIImage imageNamed:kDefaultGirlHead];
        }
    } else {
        NSURL *url = [NSURL URLWithString:_userModel.photoUrl];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        headImageView.image = image;
    }
    
    headImageView.layer.masksToBounds = YES;
    headImageView.layer.cornerRadius = 30;
    
    if (_roomType == eRoomJoin) {
        for (NSDictionary *d in _playerArray) {
            NSInteger nIndex = [d[@"index"] intValue];
            YSUserModel *model = d[@"info"];
            [self showUserViewIndex:nIndex userModel:model];
        }
        preDiceNum = _playerArray.count;
    }
    
    YSGameViewController *theVC = self;
    
    countDownView = [[YSCountDownView alloc] initWithPoint:CGPointMake(headImageView.left - 5, headImageView.top - 5)];
    countDownView.block = ^{
        [theVC->countDownView stopCountDown];
        [theVC->countDownView setHidden:YES];
        
        [theVC sendDiceInfo:theVC->preDicePoint diceCount:theVC->preDiceNum];
        // 竞猜
        NSDictionary *dict = @{@"actionCode":[YSUtility getSocketInterface:ePlayerGuess],
                               @"diceNum":[NSString stringWithFormat:@"%d",theVC->preDiceNum],
                               @"dicePoint":[NSString stringWithFormat:@"%d",theVC->preDicePoint],
                               @"gamblingId": theVC.roomModel.roomId,
                               @"uid":[YSGlobal getUID]};
        
        if (theVC.socket1.isConnected) {
            NSString *str = [YSUtility encryptSocketDict:dict];
            if (theVC.block) {
                theVC.block(ePlayerGuess);
                [theVC.socket1 writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
            }
        }
    };
    [myView sendSubviewToBack:myViewBg];
    [myView addSubview:countDownView];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kNotificationOtherStatus
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kNotificationSystemRadio
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kNotificationWeiBoShareSuccess
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kNotificationWeiBoShareFail
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kNotificationWeiXinShareSuccess
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kNotificationWeiXinShareFail
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kNotificationSocketFail
                                                  object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -

- (void)goBack {
    NSDictionary *dict = @{@"actionCode":[YSUtility getSocketInterface:ePlayerExit],
                           @"gamblingId": self.roomModel.roomId,
                           @"uid":[YSGlobal getUID]};
    if (_socket1.isConnected) {
        NSString *str = [YSUtility encryptSocketDict:dict];
        if (self.block) {
            self.block(ePlayerExit);
            [_socket1 writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (IBAction)back:(id)sender {
    if (isBeginGame) {
        [self showMsgWithTitle:@"提示" msg:@"游戏正在进行中,退出将会扣除底注幸运豆50,确定要退出吗?" delegate:self tag:100];
    } else {
        [self goBack];
    }
}

- (IBAction)soundBtnClick:(id)sender {
    if (isPlaySound) {
        isPlaySound = NO;
        [soundBtn setImage:[UIImage imageNamed:@"sound_off"] forState:UIControlStateNormal];
        if (self.delegate && [self.delegate respondsToSelector:@selector(soundOff)]) {
            [self.delegate soundOff];
        }
    } else {
        isPlaySound = YES;
        [soundBtn setImage:[UIImage imageNamed:@"sound_on"] forState:UIControlStateNormal];
        if (self.delegate && [self.delegate respondsToSelector:@selector(soundOn)]) {
            [self.delegate soundOn];
        }
    }
}

- (void)sendDiceInfo:(NSInteger)diceNum diceCount:(NSInteger)count {
    msgNumLabel.text = [NSString stringWithFormat:@"%d个",count];
    
    NSString *imageName = [NSString stringWithFormat:@"bs_%d",diceNum];
    msgBs_view.image = [UIImage imageNamed:imageName];
    
    [msgView setHidden:NO];
    
    double delayInSeconds = 1;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self sendDiceInfoDone];
    });
}

- (void)sendDiceInfoDone {
    [msgView setHidden:YES];
}

- (void)shareSuccess {
    if (shareType == eShareWeiXin) {
        [self showMsgWithTitle:@"提示" msg:@"分享朋友圈成功"];
    } else {
        [self showMsgWithTitle:@"提示" msg:@"分享微博成功"];
    }
}

- (void)shareFail {
    if (shareType == eShareWeiXin) {
        [self showMsgWithTitle:@"提示" msg:@"分享朋友圈失败"];
    } else {
        [self showMsgWithTitle:@"提示" msg:@"分享微博失败"];
    }
}

#pragma mark - user join & exit
- (void)showUserViewIndex:(NSInteger)nIndex userModel:(YSUserModel*)model{
    CGPoint point;
    switch (nIndex) {
        case eUserRightOne: {
            point = CGPointMake(viewPointX, 30);
        }
            break;
        case eUserRightTwo: {
            point = CGPointMake(UI_SCREEN_HEIGHT - userViewWidth - viewPointX, 30);
        }
            break;
        case eUserLeftOne: {
            point = CGPointMake(viewPointX, 30 + userViewHeight + 30);
        }
            break;
        case eUserLeftTwo: {
            point = CGPointMake(UI_SCREEN_HEIGHT - userViewWidth - viewPointX, 30 + userViewHeight + 20);
        }
            break;
            
        default:
            break;
    }
    
    UIView *view = [self createUserView:model andViewPoint:point];
    [self.view addSubview:view];
    [userViewArray insertObject:view atIndex:nIndex - 1];
}

- (UIView *)createUserView:(YSUserModel*)model andViewPoint:(CGPoint)point {
    YSGameUserView *view = [[YSGameUserView alloc] initWithUserMOdel:model andPoint:point];
    /////////////////////////////////
    return view;
}

- (void)userViewStopAnimate:(YSGameUserView *)view showMsg:(NSString *)msg{
    
    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [view stopAnimate];
        if (msg != nil) {
            [self showMsgWithTitle:nil msg:msg];
        }
    });
}

- (void)createUserWithInfo:(NSDictionary *)info {
    if (_playerArray.count >= 4) {
        return;
    }
    
    YSUserModel *userModel = [[YSUserModel alloc] initFromUserInfo:info];
    
    int nIndex = 1;
    if (_playerArray.count == 0) {
        [_playerArray insertObject:@{@"index":[NSString stringWithFormat:@"%d",nIndex],
                                    @"info" :userModel} atIndex:0];
    } else {
        for (; nIndex < 5; nIndex ++) {
            BOOL isHaveUser = NO;
            for (int n = 0; n < _playerArray.count ; n++) {
                NSDictionary * d = [_playerArray objectAtIndex:n];
                if ([d[@"index"] intValue] == nIndex) {
                    isHaveUser = YES;
                    break;
                }
            }
            if (!isHaveUser) {
                [_playerArray insertObject:@{@"index": [NSString stringWithFormat:@"%d",nIndex],
                                            @"info" :userModel}
                                  atIndex:nIndex - 1];
                break;
            }
        }
    }
    [self showToastMessage:[NSString stringWithFormat:@"%@ 加入游戏",userModel.name]];
    [self showUserViewIndex:nIndex userModel:userModel];
}
// 玩家退出了
- (void)userExit:(NSInteger)userId {
    // 把玩家从界面上删除
    for (YSGameUserView *view in userViewArray) {
        if ([view getUserId] == userId) {
            [view removeFromSuperview];
            [userViewArray removeObject:view];
            break;
        }
    }
    
    // 把玩家从排序数组中删除
    for (NSDictionary *dict in _playerArray) {
        YSUserModel *userModel = dict[@"info"];
        if (userModel.userId == userId) {
            [_playerArray removeObject:dict];
            [self showToastMessage:[NSString stringWithFormat:@"%@ 退出游戏",userModel.name]];
            break;
        }
    }
    
    preDiceNum = _playerArray.count;
}

- (YSUserModel *)getPleryInfoFromId:(NSInteger)userId {
    for (NSDictionary *dict in _playerArray) {
        YSUserModel *userModel = dict[@"info"];
        if (userModel.userId == userId) {
            return userModel;
        }
    }
    return nil;
};

- (void)rockDone:(YSGameUserView*)view message:(NSString *)msg {
    [view stopAnimate];
    [self showToastMessage:msg];
}

#pragma mark - GameBegin View
- (void)showGameBeginView {
    UIImage *image = [UIImage imageNamed:@"game_start"];
    CGFloat vW = image.size.width;
    CGFloat vH = image.size.height;
    
    gameBeginView = [[UIView alloc] initWithFrame:CGRectMake((UI_SCREEN_HEIGHT - vW) / 2,
                                                             (UI_SCREEN_WIDTH - vH) / 2,
                                                             vW, vH)];
    gameBeginView.backgroundColor = [UIColor clearColor];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(0, 0, vW, vH);
    
    [gameBeginView addSubview:imageView];
    [self.view addSubview:gameBeginView];
}

/**/
- (void)hideGameBeginView {
    [UIView animateWithDuration:1 animations:^{
        gameBeginView.alpha = 0;
    } completion:^(BOOL finished) {
        [gameBeginView removeFromSuperview];
        gameBeginView = nil;
    }];
}
#pragma mark - Result View
- (void)showResultView {
    if (resultView) {
        resultView = nil;
    }
    
    resultView = [[YSDieResultView alloc] initWithFrame:CGRectMake(20,
                                                                   (myView.frame.size.height - resultViewHeight)/3,
                                                                   resultViewWidth,
                                                                   resultViewHeight)
                                                 result:result];
    
    [myView addSubview:resultView];
    [resultView hideAlertView];
}

- (void)hideResultView {
    if (resultView) {
        [resultView removeFromSuperview];
        resultView = nil;
    }
}

#pragma mark - 竞猜

- (void)showQuizView:(NSDictionary *)content {
    YSGameViewController *theVC = self;
    
    quizview = [[YSSelectQuizView alloc] initWithFrame:CGRectMake((UI_SCREEN_HEIGHT - quizViewWidth)/2,
                                                                  (UI_SCREEN_WIDTH - quizViewHeight)/2,
                                                                  quizViewWidth, quizViewHeight)];
    quizview.layer.cornerRadius = 5.0;
    if (content != nil) {
        [quizview setPrePointInfo:[content[@"preDicePoint"] intValue]
                          diceNum:[content[@"preDiceNum"] intValue]];
    }
    quizview.block = ^(int upValue, int downValue) {
        [theVC->countDownView stopCountDown];
        [theVC->countDownView setHidden:YES];
        
        [theVC sendDiceInfo:downValue diceCount:upValue];
        
        NSDictionary *dict = @{@"actionCode":[YSUtility getSocketInterface:ePlayerGuess],
                               @"diceNum":[NSString stringWithFormat:@"%d",upValue],
                               @"dicePoint":[NSString stringWithFormat:@"%d",downValue],
                               @"gamblingId": theVC.roomModel.roomId,
                               @"uid":[YSGlobal getUID]};
        
        if (theVC.socket1.isConnected) {
            NSString *str = [YSUtility encryptSocketDict:dict];
            if (theVC.block) {
                theVC.block(ePlayerGuess);
                [theVC.socket1 writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
            }
        }
    };
    [self.view addSubview:quizview];
}

- (void)hideQuizView {
    [quizview removeFromSuperview];
    quizview = nil;
}

#pragma mark - 最终结果
- (void)showLastReslutView:(NSDictionary *)content {
    lastResultView = [[YSLastResultView alloc] initWithFrame:CGRectMake((UI_SCREEN_HEIGHT - lastResultViewWidth)/2,
                                                                        (UI_SCREEN_WIDTH - lastResultViewHeight)/2,
                                                                        lastResultViewWidth,
                                                                        lastResultViewHeight)
                                                 contentInfo:content];
    lastResultView.layer.cornerRadius = 5.0;
    lastResultView.delegate = self;
    
    [self.view addSubview:lastResultView];
    
    closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.frame = CGRectMake(lastResultView.right - 25/2, lastResultView.top -(25/2), 25, 25);
    [closeBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:closeBtn];
}

- (void)close {
    // 需要改变按钮状态
    gameStatus = eGameWaiting;
    [readyBtn setTitle:@"准备" forState:UIControlStateNormal];
    
    [self hideResultView];
    
    [closeBtn removeFromSuperview];
    closeBtn = nil;
    
    [lastResultView removeFromSuperview];
    lastResultView = nil;
}

#pragma mark LastResultViewDelegate
- (void)lastResultClose {
    [self close];
}

- (void)lastResultShare:(eShareType)type {
    if (type == eShareWeiXin) {
        if (![WXApi isWXAppInstalled]) {
            [self showMsgWithTitle:@"提示" msg:@"您没有安装微信客户端"];
            return;
        }
    } else {
        if (![WeiboSDK isWeiboAppInstalled]) {
            [self showMsgWithTitle:@"提示" msg:@"您没有安装微博客户端"];
            return;
        }
    }
    shareType = type;
    [[NetworkMgr sharedManager] asynchRequestWithFunId:eAPI_SHARE
                                              delegate:self
                                                params:@{@"cid":kAPP_VERSION}];
}

- (void)didSuccess:(NetworkMgr *)api userInfo:(NSDictionary *)info {
    NSInteger funId = [info[kFUN_ID] integerValue];
    NSDictionary *re = info[API_Result_RE];
    if ([YSUtility isBlankObject:re]) {
        return;
    }
    
    if (funId == eAPI_SHARE) {
        // 微信
        if (shareType == eShareWeiXin) {
            WXMediaMessage *message = [WXMediaMessage message];
            message.title = re[@"msg"];
            message.description = re[@"msg"];
            [message setThumbImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:re[@"picUrl"]]]]];
            
            WXWebpageObject *ext = [WXWebpageObject object];
            ext.webpageUrl = re[@"url"];
            
            message.mediaObject = ext;
            
            SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
            req.bText = NO;
            req.message = message;
            // 发送的目标场景，可以选择发送到会话(WXSceneSession)或者朋友圈(WXSceneTimeline)。 默认发送到会话。
            req.scene = WXSceneTimeline;
            
            [WXApi sendReq:req];
        } else {    // 微博
            WBMessageObject *objcet = [[WBMessageObject alloc] init];
            objcet.text = re[@"msg"];
            
            WBWebpageObject *webObject = [WBWebpageObject object];
            webObject.objectID = @"yedianshaiwang200";
            webObject.title = @"夜店骰王";
            webObject.webpageUrl = re[@"url"];
            webObject.thumbnailData = [NSData dataWithContentsOfURL:[NSURL URLWithString:re[@"picUrl"]]];
            objcet.mediaObject = webObject;
            
            WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:objcet];
            
            [WeiboSDK sendRequest:request];
        }
    }
}

#pragma mark -
- (void)updateUserScore:(NSString *)score {
    if (![YSUtility isBlankObject:score]) {
        NSInteger temp = [_userModel.scoreAmount integerValue];
        temp = temp + [score integerValue];
        _userModel.scoreAmount = [NSString stringWithFormat:@"%d",temp];
        [_userModel saveUserInfo];
    }
    
    userScore.text = [NSString stringWithFormat:@"幸运豆:%@",_userModel.scoreAmount];
}

- (IBAction)readyBtnClick:(id)sender {
    if (gameStatus == eGameReady) {
        return;
    }
    
    NSDictionary *dict;
    if (gameStatus == eGameWaiting) {
        // 调用准备
        dict = @{@"actionCode":[YSUtility getSocketInterface:ePlayerReady],
                 @"gamblingId": self.roomModel.roomId,
                 @"uid":[YSGlobal getUID]};
        
    } else if (gameStatus == EGameOpen) {
        // 调用开
        [self hideQuizView];
        
        dict = @{@"actionCode":[YSUtility getSocketInterface:ePlayerOpen],
                 @"gamblingId": self.roomModel.roomId,
                 @"uid":[YSGlobal getUID]};
    }
    
    if (_socket1.isConnected) {
        NSString *str = [YSUtility encryptSocketDict:dict];
        if (self.block) {
            self.block([dict[@"actionCode"] integerValue]);
            [_socket1 writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
        }
    }
}

#pragma mark - yaoyiyao
- (void)startAnimate {
    CGFloat rotation = 0.3;
    
    CABasicAnimation *shake = [CABasicAnimation animationWithKeyPath:@"transform"];
    shake.duration = 0.13;
    shake.autoreverses = YES;
    shake.repeatCount  = MAXFLOAT;
    shake.removedOnCompletion = NO;
    shake.fromValue = [NSValue valueWithCATransform3D:CATransform3DRotate(boxImageView.layer.transform,-rotation, 0.0 ,0.0 ,1.0)];
    shake.toValue = [NSValue valueWithCATransform3D:CATransform3DRotate(boxImageView.layer.transform, rotation, 0.0 ,0.0 ,1.0)];
    
    [boxImageView.layer addAnimation:shake forKey:@"shakeAnimation"];
}

- (void)stopAnimate {
    [boxImageView.layer removeAnimationForKey:@"shakeAnimation"];
}

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (gameStatus != eGameReady) {
        return;
    }
    
    [self hideGameBeginView];
    [self startAnimate];
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (!isBeginGame) {
        return;
    }
    
    [self hideGameBeginView];
    [YSUtility playSound:@"rock" soundType:@"mp3"];
    [self startAnimate];
    AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
    
    [NSTimer scheduledTimerWithTimeInterval:1.0f
                                     target:self
                                   selector:@selector(yaoYiYao)
                                   userInfo:nil
                                    repeats:NO];
    // 1.5秒动画停止
    [NSTimer scheduledTimerWithTimeInterval:1.5f
                                     target:self
                                   selector:@selector(stopAnimate)
                                   userInfo:nil
                                    repeats:NO];
}

- (void)yaoYiYao {
    
    result = nil;
    
    for (int i = 0; i < 5; i++) {
        NSInteger temp = [YSUtility getRandomNumber:1 to:6];
        if (result.length == 0) {
            result = [NSMutableString stringWithFormat:@"%d",temp];
        } else {
            [result appendString:[NSString stringWithFormat:@"-%d",temp]];
        }
    }
    
    NSDictionary *dict = @{@"dicePoint":result,
                           @"actionCode":[YSUtility getSocketInterface:ePlayerBegin],
                           @"gamblingId": self.roomModel.roomId,
                           @"uid":[YSGlobal getUID]};
    
    if (_socket1.isConnected) {
        NSString *str = [YSUtility encryptSocketDict:dict];
        if (self.block) {
            self.block(ePlayerBegin);
            isBeginGame = NO;
            [_socket1 writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
        }
    }
}

#pragma mark - Socket Notification
- (void)socketRadioNotification:(NSNotification *)notification {
    NSDictionary *dict = notification.userInfo;
    NSInteger code = [dict[@"code"] intValue];
    NSDictionary *content = dict[@"content"];
    
    switch (code) {
        case eSocketRadioPlayerJoin:    // 玩家加入
        {
            preDiceNum = preDiceNum + 1;
            [self createUserWithInfo:content];
        }
            break;
        case eSocketRadioPlayerExit:    // 玩家退出
        case eSocketRadioPlayerDown:    // 玩家掉线
        {
            [self userExit:[content[@"id"] intValue]];
        }
            break;
        case eSocketRadioGameBegin:     // 游戏开始
        {
            [YSUtility playSound:@"start" soundType:@"wav"];
            // 去掉所有人的准备状态
            for (YSGameUserView *view in userViewArray) {
                [view hideReady];
            }
            [self showGameBeginView];
            isBeginGame = YES;
        }
            break;
        case eSocketRadioPlayerReady:   // 玩家准备
        {
            NSInteger userId = [content[@"id"] intValue];
            for (YSGameUserView *v in userViewArray) {
                if ([v getUserId] == userId) {
                    [v showReady];
                }
            }
        }
            break;
        case eSocketRadioPlayerDone:
        {
            NSInteger doneUserId = [content[@"id"] integerValue];
            YSUserModel *m = [self getPleryInfoFromId:doneUserId];
            for (YSGameUserView *view in userViewArray) {
                if (m.userId == [view getUserId]) {
                    [view startAnimate];
                    NSString *msg = [NSString stringWithFormat:@"%@已经摇完",m.name];

                    double delayInSeconds = 2;
                    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
                    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                        [self rockDone:view message:msg];
                    });
                }
            }
        }
            break;
        case eSocketRadioQuizBegin:     // 玩家竞猜
        {
            NSInteger tokenUserId = [content[@"tokenUserId"] integerValue];
            
            if (tokenUserId == self.userModel.userId) {
                [self showQuizView:nil];
                [countDownView beginCountDown];
                readyBtn.hidden = YES;
            } else {
                for (YSGameUserView *view in userViewArray) {
                    if ([view getUserId] == tokenUserId) {
                        [view beginCountDown];
                        break;
                    }
                }
            }
        }
            break;
        case eSocketRadioQuizDone:     // 玩家竞猜完成
        {
            NSLog(@"yyy  %@",content);
            // 清除倒计时
            for (YSGameUserView *view in userViewArray) {
                [view stopCountDown];
            }
            readyBtn.hidden = YES;
            
            NSInteger preUserId = [content[@"preUserId"] integerValue];
            NSInteger tokenUserId = [content[@"tokenUserId"] integerValue];
            
            for (YSGameUserView *view in userViewArray) {
                if ([view getUserId] == preUserId) {
                    [view showDiceView:[content[@"preDicePoint"] integerValue]
                                number:[content[@"preDiceNum"] integerValue]];
                }
            }
            
            if (tokenUserId == self.userModel.userId) {
                [self showQuizView:content];
                // 可以点开
                gameStatus = EGameOpen;
                [readyBtn setTitle:@"开" forState:UIControlStateNormal];
                readyBtn.hidden = NO;
                
                [countDownView beginCountDown];
                [countDownView setHidden:NO];
                
            } else {
                [self hideQuizView];
                for (YSGameUserView *view in userViewArray) {
                    [view stopCountDown];
                    if ([view getUserId] == tokenUserId) {
                        [view beginCountDown];
                    }
                }
            }
            
            preDiceNum = [content[@"preDiceNum"] intValue];
            preDicePoint = [content[@"preDicePoint"] intValue];
            
            if (preDicePoint == 6) {
                preDiceNum ++;
                preDicePoint = 1;
            } else {
                preDicePoint ++;
            }
        }
            break;
            
        case eSocketRadioGameOver: {    // 游戏完成
            [self updateUserScore:content[@"score"]];
            [countDownView stopCountDown];
            for (YSGameUserView *view in userViewArray) {
                [view stopCountDown];
            }
            
            if ([content[@"win"] intValue] == eResultWin) {
                [YSUtility playSound:@"win" soundType:@"mp3"];
            } else {
                [YSUtility playSound:@"lose" soundType:@"mp3"];
            }
            
            [self showLastReslutView:content];
            
            gameStatus = eGameWaiting;
            [readyBtn setTitle:@"准备" forState:UIControlStateNormal];
            readyBtn.hidden = NO;
        }
            break;
        default:
            break;
    }
}

- (void)socketOtherStatus:(NSNotification *)notification {
    if (gameStatus == eGameWaiting) {
        gameStatus = eGameReady;
        [readyBtn setTitle:@"已准备" forState:UIControlStateNormal];
    }
    
    NSDictionary *dict = notification.userInfo;
    NSInteger code = [dict[@"code"] intValue];
    switch (code) {
        case ePlayerBegin:
        {
            // 骰子结果
            [self stopAnimate];
            [self showResultView];
        }
            break;
        case ePlayerGuess:
        {
            // 竞猜结果
        }
            break;
        case ePlayerExit:
        {
           
        }
            break;
        default:
            break;
    }
}

- (void)socketFail:(NSNotification *)notification {
    [self showToastMessage:notification.userInfo[@"msg"]];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex != alertView.cancelButtonIndex) {
        [self goBack];
    }
}
@end
